package server

import (
	"9-13yk/common/model/mysql"
	"9-13yk/common/proto/user"
	"9-13yk/common/util"
	"errors"
	jwt "github.com/golangblogs/gojwt"
	"gorm.io/gorm"
)

func Login(req *user.LoginReq) (*user.LoginResp, error) {
	getUser, err := mysql.GetUser(req.Phone)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	if getUser.Phone == "" {
		m := mysql.User{
			Model:    gorm.Model{},
			Phone:    req.Phone,
			Password: util.Md5(req.Password),
		}
		err := mysql.CreateUser(&m)
		if err != nil {
			return nil, errors.New("注册失败")
		}
	}
	if getUser.Password != util.Md5(req.Password) {
		return nil, errors.New("密码错误")
	}
	claims := jwt.CustomClaims{ID: getUser.ID}
	token, err := jwt.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		return nil, errors.New("token生成失败")
	}
	return &user.LoginResp{Greet: token}, nil
}
